import pandas as pd # 导入数据分析模块
import numpy as np # 导入科学计算模块

from pyecharts.charts import Bar,Map,Line,Pie,Grid,Timeline # 导入条形图,地图,折线图,玫瑰图 ,grid并行组图组件
from pyecharts import options as opts # 导入配置项模块
from pyecharts.globals import ThemeType # 导入主题模块

data = pd.read_csv('china_all_provinces_history_data_2022_07_19.csv')# 读取数据,
data['date'] = pd.to_datetime(data['date']) # 将日期这一列数据,设置为datatime64[ns]格式
data.set_index('date',inplace=True) # 将日期设置为索引

date_list  = pd.DataFrame(pd.date_range('2020-03-01','2022-07-01',freq='15D'))
date_list = date_list[0].apply(lambda x:x.strftime('%Y-%m-%d'))
data_list = {}
for i in date_list:
    data_list[i] = data.loc[i,['province_name','total_confirm']].sort_values(by='total_confirm').values.tolist()[::-1]

data3 = pd.read_csv('world_all_country_history_data_2022_07_19.csv')

data4 = data3[data3['country_name'] == '中国']
cn_data = data4.copy()
cn_data['date'] = pd.to_datetime(cn_data['date']) # 将日期这一列数据,设置为datatime64[ns]格式
cn_data.set_index('date',inplace=True) # 将日期设置为索引

date_list  = pd.DataFrame(pd.date_range('2020-03-01','2022-07-01',freq='15D'))
date_list = date_list[0].apply(lambda x:x.strftime('%Y-%m-%d'))
cn_data_list = [[date,cn_data.loc[date,'total_confirm']] for date in date_list]

marker_data = []
for i,j  in enumerate(date_list):
    md_data =  [0] * len(cn_data_list)
    md_data[i] = int(dict(cn_data_list)[j])
    marker_data.append(md_data)

t1 = Timeline(init_opts=opts.InitOpts(theme=ThemeType.CHALK, width='1530px', height='700px'))
for z, date in enumerate(date_list):
    # 条形图
    bar = (Bar(init_opts=opts.InitOpts(theme=ThemeType.DARK))
           .add_xaxis([i[0] for i in data_list[date][2:]])
           .add_yaxis('累计确诊', [i[1] for i in data_list[date]][2:])
           .set_global_opts(title_opts=opts.TitleOpts(title= '中国累计确诊人数条形图',
                                                      pos_left='83%', pos_top='2%',
                                                      title_textstyle_opts=opts.TextStyleOpts(font_size=14),

                                                      ),
                            legend_opts=opts.LegendOpts(pos_top='6%', pos_left='6.5%', is_show=False,
                                                        textstyle_opts=opts.TextStyleOpts(color='white')),
                            datazoom_opts=opts.DataZoomOpts(is_show=True, range_start=0, range_end=20, pos_top='45%', ),
                            xaxis_opts=opts.AxisOpts(name='',
                                                     type_='category',  # 轴的类型
                                                     name_location='center',  # 坐标轴轴名称的位置
                                                     name_gap=10,  # 坐标轴轴名称距离轴线的距离
                                                     axislabel_opts=opts.LabelOpts(color='white', is_show=True),
                                                     # 坐标轴标签的颜色

                                                     axistick_opts=opts.AxisTickOpts(is_show=True,  # 是否显示坐标轴刻度线
                                                                                     is_inside=True,  # 刻度线是否朝内
                                                                                     # 坐标轴刻度线的样式
                                                                                     linestyle_opts=opts.LineStyleOpts(
                                                                                         color='cyan')),
                                                     axisline_opts=opts.AxisLineOpts(symbol=['none', 'arrow'],
                                                                                     # 坐标轴的箭头的方向
                                                                                     # 坐标轴轴线的颜色
                                                                                     linestyle_opts=opts.LineStyleOpts(
                                                                                         color='cyan'))
                                                     ),
                            yaxis_opts=opts.AxisOpts(name='人数',  # x轴的名称
                                                     type_='value',  # 轴的类型
                                                     name_location='center',  # 坐标轴轴名称的位置
                                                     name_gap=10,  # 坐标轴轴名称距离轴线的距离
                                                     axislabel_opts=opts.LabelOpts(color='cyan', is_show=False),
                                                     # 坐标轴标签的颜色
                                                     axistick_opts=opts.AxisTickOpts(is_show=True,  # 是否显示坐标轴刻度线
                                                                                     is_inside=True,  # 刻度线是否朝内
                                                                                     # 坐标轴刻度线的样式
                                                                                     linestyle_opts=opts.LineStyleOpts(
                                                                                         color='cyan')),
                                                     axisline_opts=opts.AxisLineOpts(symbol=['none', 'arrow'],
                                                                                     # 坐标轴的箭头的方向
                                                                                     # 坐标轴轴线的颜色
                                                                                     linestyle_opts=opts.LineStyleOpts(
                                                                                         color='cyan'))
                                                     ),
                            # ----- 视觉映射配置项目
                            visualmap_opts=opts.VisualMapOpts(is_piecewise=True,
                                                              is_show=False,
                                                              range_text=['Highe', 'Low'],
                                                              textstyle_opts=opts.TextStyleOpts(color='cyan'),

                                                              # 设置分段颜色
                                                              max_=100000,  # 最大值
                                                              pos_right='1%',
                                                              pos_top='center',

                                                              ),

                            )
           )

    # 玫瑰图
    pie = (Pie(init_opts=opts.InitOpts(theme=ThemeType.CHALK))  # 设置图表主题
           .add('', data_list[date],  # 系列名称设置为空,数据项考虑到前五个数据太大,因此将其移除
                radius=['10%', '35%'],  # 设置内环半径和外环半径
                center=['15%', '65%'],
                rosetype='area',  # 图表的类型,
                label_opts=opts.LabelOpts(formatter="{b}:{c}人"),  # 数据标签设置项
                )
           .set_global_opts(title_opts=opts.TitleOpts(title='全国各省累计确诊人数玫瑰图',
                                                      pos_left='7.8%',
                                                      pos_top='37%',title_textstyle_opts=opts.TextStyleOpts(font_size=15)),  # 设置图表标题
                            legend_opts=opts.LegendOpts(is_show=False))  # 关闭图例显示
           )
    # 地图
    subtitle = f'当前是2022年7月4日,当前确诊人数最多的地区为{data_list[date][0][0]},确诊人数为{data_list[date][0][1]}人'
    map_ = (Map(init_opts=opts.InitOpts(theme=ThemeType.CHALK))  # 实例化一个地图对象
            .add(series_name="累计确诊",  # 数据的系列名称
                 data_pair=data_list[date],  # 具体的数据,嵌套列表形式
                 maptype='china',  # 地图的类型
                 label_opts=opts.LabelOpts(color='#fcfcfc',  # 调整地图上面文字的颜色
                                           font_weight='bold',  # 调整地图上面文字的粗细
                                           font_size=12,  # # 调整地图上面文字的大小
                                           font_family='SimHei'
                                           ),
                 center=[100, 36],  # 调整图表的位置
                 is_map_symbol_show=False,  # 取消地图上面的标点信息
                 )
            .set_global_opts(title_opts=opts.TitleOpts('全国各省累计确诊人数地图',
                                                       subtitle=subtitle,
                                                       pos_left='center',

                                                       title_textstyle_opts=opts.TextStyleOpts(font_size=20, ),
                                                       subtitle_textstyle_opts=opts.TextStyleOpts(font_size=16,
                                                                                                  color='white'
                                                                                                  )
                                                       ),
                             legend_opts=opts.LegendOpts(is_show=False),
                             visualmap_opts=opts.VisualMapOpts(is_piecewise=True,  # 颜色条是否分段
                                                               pieces=[
                                                                   {'min': 10000, 'color': '#7f1100'},
                                                                   {'min': 1000, 'max': 9999, 'color': '#bd1316'},
                                                                   {'min': 500, 'max': 999, 'color': '#e64b45'},
                                                                   {'min': 100, 'max': 499, 'color': '#ff8c71'},
                                                                   {'min': 1, 'max': 99, 'color': '#fdd2a0'},
                                                               ],
                                                               pos_left='5%', pos_top='center',
                                                               range_text=['高', '低'],
                                                               dimension=0,
                                                               textstyle_opts=opts.TextStyleOpts(color='white')
                                                               ),
                             )
            )
    line = (Line(init_opts=opts.InitOpts(theme=ThemeType.CHALK))
            .add_xaxis([i[0] for i in cn_data_list])
            .add_yaxis('新增确诊', [int(i[1]) for i in cn_data_list],
                       symbol='circle',
                       symbol_size=5,
                       label_opts=opts.LabelOpts(is_show=False),
                       is_smooth=True,
                       )
            .add_yaxis('', marker_data[z],  # 气泡系列数据,
                       label_opts=opts.LabelOpts(is_show=False),
                       symbol_size=0,
                       linestyle_opts=opts.LineStyleOpts(is_show=False, width=0),
                       markpoint_opts=opts.MarkPointOpts(symbol_size=[60, 60],
                                                         data=[opts.MarkLineItem(type_='max')])
                       )
            .set_global_opts(title_opts=opts.TitleOpts(title='全国每日新增确诊人数时序折线图',
                                                       pos_left='80%', pos_right='1%', pos_bottom='43%',
                                                       title_textstyle_opts=opts.TextStyleOpts(font_size=16)),  # 标题字体大小
                             xaxis_opts=opts.AxisOpts(name='日期',  # 坐标轴名称
                                                      name_gap=20,  # 坐标轴名称距离坐标轴的位置
                                                      name_textstyle_opts=opts.TextStyleOpts(color='cyan',  # 坐标轴名称字体颜色,
                                                                                             font_size=10),  # 字体大小
                                                      axislabel_opts=opts.LabelOpts(color='cyan'),  # 坐标轴标签的颜色
                                                      axisline_opts=opts.AxisLineOpts(is_show=True,  # 坐标轴轴线配置项目.
                                                                                      symbol=['none', 'arrow'],
                                                                                      # 设置右端箭头
                                                                                      #  设置轴线的颜色
                                                                                      linestyle_opts=opts.LineStyleOpts(
                                                                                          color='cyan')),
                                                      ),  # x轴配置项目结束
                             yaxis_opts=opts.AxisOpts(name='新增确诊人数',  # 坐标轴名称
                                                      min_=0,
                                                      name_textstyle_opts=opts.TextStyleOpts(color='cyan',  # 坐标轴名称字体颜色,
                                                                                             font_size=10),  # 字体大小
                                                      axislabel_opts=opts.LabelOpts(color='cyan'),  # 坐标轴标签的颜色
                                                      axisline_opts=opts.AxisLineOpts(is_show=True,  # 坐标轴轴线配置项目.
                                                                                      #  设置轴线的颜色
                                                                                      linestyle_opts=opts.LineStyleOpts(
                                                                                          color='cyan')),

                                                      ),
                             tooltip_opts=opts.TooltipOpts(trigger='axis', axis_pointer_type='cross'),
                             axispointer_opts=opts.AxisPointerOpts(is_show=True,
                                                                   label=opts.LabelOpts(color='black',
                                                                                        font_size=12,
                                                                                        font_family='SimHei')),
                             legend_opts=opts.LegendOpts(is_show=False),
                             )
            )
    # pos_left = '67%', pos_right = '8%', pos_bottom = '55%', pos_top = '8%
    grid = (Grid(init_opts=opts.InitOpts(theme=ThemeType.CHALK, width='1200px', height='600px'))
            .add(bar,  # 条形图
                 grid_opts=opts.GridOpts(pos_left = '79%', pos_right = '1%', pos_bottom = '55%', pos_top = '8%'),
                 is_control_axis_index=True,
                 )
            .add(line,  # 添加折线图
                 grid_opts=opts.GridOpts(pos_left='79%', pos_right='1%', pos_bottom='5%', pos_top='60%'),
                 )
            .add(pie,  # 添加玫瑰图
                 grid_opts=opts.GridOpts()
                 )
            .add(map_,  # 添加地图
                 grid_opts=opts.GridOpts(is_contain_label=True))
            )
    t1.add(grid, f'{date}')
    t1.add_schema(play_interval=330,  # 设置播放速度
                  is_loop_play=False,  # 是否循环播放
                  orient='horizontal',  #
                  pos_left='5%',
                  pos_right='30%',
                  pos_bottom='2%'

                  )
t1.render('finall_work.html')